#include "control.h"
#include "global.h"
#include "util.h"
#include "glhead.h"
#include "mtxlib.h"
#include <vector>
#include <math.h>
#include<iostream>  
#include<fstream>  

using namespace std;



int buttons[5] ={ GLUT_UP, GLUT_UP, GLUT_UP, GLUT_UP, GLUT_UP};

void passive_motion (int x, int y){

}

vector3 GetXY(float mouse_x, float mouse_y){
	
	vector3 near_point, far_point, x_point, vector;
	GLdouble k = 1.0;
	GLdouble modelview[16];
	GLdouble projection[16];
	GLint    viewport[4];
	glGetDoublev(GL_MODELVIEW_MATRIX,modelview);
	glGetDoublev(GL_PROJECTION_MATRIX,projection);
	glGetIntegerv(GL_VIEWPORT,viewport);

	GLdouble world_x, world_y, world_z;
    // get the near plane's point of intersection(z=0.0)
	gluUnProject( (GLdouble) mouse_x, (GLdouble) mouse_y, 0, 
                    modelview, projection, viewport, 
                    &world_x, &world_y, &world_z);
	near_point.set(float(world_x), float(world_y), float(world_z));

	// get the far plane's point of intersection(z=1.0)
	gluUnProject( (GLdouble) mouse_x, (GLdouble) mouse_y, 1, 
                    modelview, projection, viewport, 
                    &world_x, &world_y, &world_z); 
    far_point.set(float(world_x), float(world_y), float(world_z));
	vector.set(near_point.x-far_point.x,near_point.y-far_point.y,near_point.z-far_point.z);
	k = (far_point.z)/vector.z;
	if(k<0) k=-k;
	x_point.set((float)far_point.x+(float)k*vector.x,-(float)far_point.y-(float)k*vector.y,0);
	return x_point;
}

void motion (int x, int y){
	if (buttons[GLUT_LEFT_BUTTON] == GLUT_DOWN){
		vector3 src = GetXY(last_x,last_y);
		vector3 des = GetXY(x,y);
		glo->rotate(src,des);
	}
	last_x = x;
	last_y = y;
}

void mouse (int button,int state,int x,int y){
	buttons[button] = state;
	if(state == GLUT_DOWN){
		last_x = x;
		last_y = y;
	}else if(state == GLUT_UP){
		
	}

}

void keyboard(unsigned char key, int x, int y){

	switch (key){
	case 'b':
		break;
	}
}

void special_keys(int key, int x, int y){
	switch (key){
	case GLUT_KEY_F1:

		break;
	}
}   